import React from 'react'
import classnames from 'classnames'

export default class Header extends React.Component {
  constructor() {
    super()
    this.handleScroll = this.handleScroll.bind(this)
    this.getScrollTop = this.getScrollTop.bind(this)
    let isScroll = false
    if (!!this.getScrollTop()) {
      isScroll = true
    }
    this.state = {
      isScroll
    }
  }
  componentDidMount() {
    this.attachEvents()
  }
  componentWillUnmount() {
    this.detachEvents()
  }
  render() {
    let { props, state } = this
    let { options } = props
    let { isScroll } = state
    let { title } = options
    // 当 iosApp下添加 class="index_header_iosapp"
    return (
      <div
        className="lists_title_box"
        className={classnames('lists_title_box', {
          'index_header_scroll': isScroll
        })}
      >
        <span className="go_back">
          <i className="goback_icon" />
        </span>
        <h1 className="list_title_text">{title}</h1>
      </div>
    )
  }
  attachEvents() {
    window.addEventListener('scroll', this.handleScroll)
  }
  detachEvents() {
    window.removeEventListener('scroll', this.handleScroll)
  }
  handleScroll() {
    let scrollTop = this.getScrollTop()
    if (scrollTop > 26) {
      this.setState({
        isScroll: true
      })
    } else if (scrollTop === 0) {
      this.setState({
        isScroll: false
      })
    }
  }
  getScrollTop() {
    let { props } = this
    if (!props || !props.isClient) {
      return
    }
    let { isClient } = props
    if (!isClient) {
      return
    }
    return window.pageYOffset !== undefined
      ? window.pageYOffset
      : (document.documentElement || document.body.parentNode || document.body)
        .scrollTop
  }
}